<?php
/**
 * Created by PhpStorm.
 * User: PHP
 * Date: 2017/12/29
 * Time: 16:48
 */
namespace app\index\controller;

use app\index\model\Member;
use think\Controller;
use think\Db;

class Sign extends Controller
{
    /**
     * 授权登录
     *
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     * @author   [小码哥]
     */
    public function sign_in()
    {
        // 公众号APPID
        $wxConfig = config('wx');
        $appid      = $wxConfig['appid'];
        $app_secret = $wxConfig['app_secret'];
        // 回调地址
        $redirect_uri = urlencode('http://yunnan.lihui11.cc/index/sign/sign_in');
        // 类型 snsapi_base 无需授权只能获取openid、snsapi_userinfo 获取基本信息、需要授权
        $scope = 'snsapi_userinfo';
        if(isset($_GET['code'])){
            $code   = $_GET['code'];//获取code
            $weixin = file_get_contents("https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$app_secret}&code={$code}&grant_type=authorization_code");
            // echo '<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no">';
            //通过code换取网页授权access_token
            $array         = json_decode($weixin, true); //对JSON格式的字符串进行编码
            $refresh_token = $array['refresh_token'];
            $access_token  = $array['access_token'];
            if(!cache('access_token')){
                // 刷新access_token
                $reloadAccessToken = file_get_contents("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={$appid}&grant_type=refresh_token&refresh_token={$array['refresh_token']}");
                $reloadAccessToken = json_decode($reloadAccessToken, true);
                $refresh_token     = $reloadAccessToken['refresh_token'];
                $access_token      = $reloadAccessToken['access_token'];
            }
            $result = file_get_contents("https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$array['openid']}&lang=zh_CN");
            $result = json_decode($result, true);
            // dump($result);
            // $jsapi_ticket = file_get_contents("http://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token={$access_token}&type=jsapi");
            // $jsapi_ticket = json_decode($jsapi_ticket, true);
            cache('access_token', $access_token, 7200);
            cache('refresh_token', $refresh_token);
            if($result){
                // openid
                $Mebmer = new Member();
                $openid = $result['openid'];
                $check  = Db::name('Member')->where(['openid' => $openid])->find();
                if($check){
                    cache($openid, 1, (60 * 60 * 24));
                    session('member', $check);
                    session('openid', $openid);
                    if($result['nickname'] != $check['nickname']){
                        Db::name('Member')->where(['openid' => $openid])->setField(['nickname' => $result['nickname']]);
                    }
                    if($result['headimgurl'] != $check['head_img']){
                        Db::name('Member')->where(['openid' => $openid])->setField(['head_img' => $result['headimgurl']]);
                    }
                    $this->redirect(url('index/index'));
                }else{
                    $param = [
                        'openid'   => $openid,
                        'head_img' => $result['headimgurl'],
                        'province' => $result['province'],
                        'city'     => $result['city'],
                        'nickname' => $result['nickname'],
                        'sex'      => $result['sex'],
                        'account'  => strtoupper(random_str(8))
                    ];
                    $res   = $Mebmer->insertMember($param);
                    if($res['code'] == 200){
                        cache($openid, 1, (60 * 60 * 24));
                        session('member', $res['data']);
                        session('openid', $openid);
                        $this->redirect(url('index/index'));
                    }
                    $this->redirect(url('sign/sign_in'));
                }
            }
        }else{
            // 请求地址1
            $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$redirect_uri}&response_type=code&scope={$scope}&state=123#wechat_redirect";
            $this->redirect($url);
        }
    }

    /**
     * 完善资料第一步
     *
     * @return mixed
     * @author   [小码哥]
     */
    public function step_one()
    {
        if(request()->isPost()){
            $param = input('post.');
            if(cache($param['mobile'] != $param['code'])){
                return json(['code' => 0, 'data' => null, 'msg' => '验证码不正确']);
            }
            unset($param['code']);
            $Member = new Member();
            $result = $Member->updateUser($param, 'id');
            return json($result);
        }
        return $this->fetch('step_one', ['user' => session('member')]);
    }

    /**
     * 获取验证码
     *
     * @return \think\response\Json
     * @author   [小码哥]
     */
    public function get_code()
    {
        $mobile = input('mobile');
        $code   = mt_rand(1000, 9999);
        cache($mobile, $code);
        return json(['code' => 200, 'data' => $code, 'msg' => '已发送、请注意查收']);
    }

    /**
     * 数据签名
     *
     * @return \think\response\Json
     * @author   [小码哥]
     */
    public function sign()
    {
        $param = input('post.');
        ksort($param);
        $number     = 0;
        $signString = '';
        foreach($param as $key => $item){
            $signString .= ($number === 0) ? "{$key}={$item}" : "&{$key}={$item}";
            $number++;
        }
        $signString = sha1($signString);
        return json(['code' => 200, 'data' => $signString, 'msg' => '签名成功']);
    }

    /**
     * 创建带参数的二维码
     *
     * @author   [小码哥]
     */
    public function getRecode()
    {
        $wxConfig = config('wx');
        $appid      = $wxConfig['appid'];
        $app_secret = $wxConfig['app_secret'];
        if(isset($_GET['code'])){
            $code   = $_GET['code'];//获取code
            $weixin = file_get_contents("https://api.weixin.qq.com/sns/oauth2/access_token?appid={$appid}&secret={$app_secret}&code={$code}&grant_type=authorization_code");
            echo '<meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1,user-scalable=no">';
            //通过code换取网页授权access_token
            $array         = json_decode($weixin, true); //对JSON格式的字符串进行编码
            $refresh_token = $array['refresh_token'];
            $access_token  = $array['access_token'];
            if(!cache('access_token')){
                // 刷新access_token
                $reloadAccessToken = file_get_contents("https://api.weixin.qq.com/sns/oauth2/refresh_token?appid={$appid}&grant_type=refresh_token&refresh_token={$array['refresh_token']}");
                $reloadAccessToken = json_decode($reloadAccessToken, true);
                $refresh_token     = $reloadAccessToken['refresh_token'];
                $access_token      = $reloadAccessToken['access_token'];
            }
            $result = file_get_contents("https://api.weixin.qq.com/sns/userinfo?access_token={$access_token}&openid={$array['openid']}&lang=zh_CN");
            $result = json_decode($result, true);
            cache('access_token', $access_token, 7200);
            cache('refresh_token', $refresh_token);
            // halt($result);
            return $result;
        }else{
            $this->getD();
        }
        //{"expire_seconds": 604800, "action_name": "QR_SCENE", "action_info": {"scene": {"scene_id": 123}}}
    }

    public function getD()
    {
        $wxConfig = config('wx');
        $appid      = $wxConfig['appid'];
        $app_secret = $wxConfig['app_secret'];
        // 回调地址
        $redirect_uri = urlencode('http://yunnan.lihui11.cc/Index/Index/extends_code');
        // 类型 snsapi_base 无需授权只能获取openid、snsapi_userinfo 获取基本信息、需要授权
        $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid={$appid}&redirect_uri={$redirect_uri}&response_type=code&scope=snsapi_base&state=123#wechat_redirect";
        $this->redirect($url);
    }
}